package com.acs.attestation.util;

import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;

import java.util.List;

/**
 * @author lj
 * @date 2019-02-26
 * @description Bean转换工具类
 */
public class BeanUtil extends BeanUtils {

    public static <S, T> List<T> fromBeans(List<S> sources, Class<T> targetClass) {
        List<T> targetList = Lists.newArrayList();
        if (sources == null || sources.size() == 0) {
            return targetList;
        }
        sources.forEach(source -> {
            T target = fromBean(source, targetClass);
            if (target != null) {
                targetList.add(target);
            }
        });
        return targetList;
    }

    public static <S, T> T fromBean(S source, Class<T> targetClass) {
        return fromBean(source, targetClass, (String[]) null);
    }

    public static <S, T> T fromBean(S source, Class<T> targetClass, String... ignoreProperties) {
        if (source == null) {
            return null;
        }
        T target;
        try {
            target = targetClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("目标类实例化异常", e);
        }
        if (target != null) {
            BeanUtils.copyProperties(source, target, ignoreProperties);
        }
        return target;
    }
}
